#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>

#define BUFSIZE 512

int main(int argc, char *argv[]) {
    if (argc != 3) {
        printf("Usage : %s <IP> <port>\n", argv[0]);
        exit(1);
    }
    
    int client_sock;
    client_sock = socket(PF_INET, SOCK_STREAM, 0);

    struct sockaddr_in serv_addr;
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = inet_addr(argv[1]);
    serv_addr.sin_port = ntohs(atoi(argv[2]));

    int rs = connect(client_sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
    assert(rs != -1);
    char buf[BUFSIZE];
    while (1) {
        fputs("input message (q to quit): \n", stdout);        
        fgets(buf, BUFSIZE, stdin);
        if (strcmp(buf, "q\n") == 0) 
            break;

        // 一次能否写完？？？
        // 是否需要循环写？
        send(client_sock, buf, strlen(buf), 0);
        int len = recv(client_sock, buf, BUFSIZE - 1, 0);
        buf[len] = 0;
        printf("Message from server: %s\n", buf);
    }
    close(client_sock);


    return 0;
}